Skip to main content
Version: v1.4.1

Telco Churn Prediction with Refactored Xplainable Client

This notebook demonstrates the complete ML workflow using the new refactored Xplainable client with:

  • Type-safe Pydantic models
  • Comprehensive error handling
  • Service-oriented architecture
  • All new client endpoints
  • Robust production patterns

We'll predict customer churn using the IBM Telco dataset while showcasing:

  • Models Service: Type-safe model creation and management
  • Deployments Service: Model deployment with proper error handling
  • Preprocessing Service: Pipeline management and data transformation
  • Autotrain Service: AI-powered automated training workflows
  • Inference Service: Predictions and explanations
  • GPT Service: AI-generated insights and reports
  • Datasets Service: Data management and loading
  • Misc Service: Health checks and utilities

Package Installation and Imports

1# Install required packages
2!pip install xplainable pandas scikit-learn requests xplainable-client
1# Standard imports
2import pandas as pd
3import numpy as np
4import json
5import warnings
6from typing import Optional, Dict, Any, List
7from datetime import datetime
8
9# Xplainable core imports
10import xplainable as xp
11from xplainable.core.models import XClassifier
12from xplainable.core.optimisation.bayesian import XParamOptimiser
13from xplainable_preprocessing import PipelineSpec, StepSpec, compile_spec
14
15# Sklearn imports
16from sklearn.model_selection import train_test_split
17
18# Refactored Xplainable Client imports (NEW!)
19from xplainable_client.client.client import XplainableClient
20from xplainable_client.client.base import XplainableAPIError
21from xplainable_client.client.py_models.models import CreateModelResponse
22from xplainable_client.client.py_models.deployments import CreateDeploymentResponse
23from xplainable_client.client.py_models.preprocessing import CreatePreprocessorResponse
24from xplainable_client.client.py_models.autotrain import DatasetSummary, TextGenConfig
25from xplainable_client.client.py_models.inference import PredictionResponse
26
27# Suppress warnings for cleaner output
28warnings.filterwarnings('ignore')
29
30print(f"Xplainable version: {xp.__version__}")
31print(f"All imports successful!")

Initialize Refactored Xplainable Client

The new client provides:

  • Service separation: client.models, client.deployments, etc.
  • Type safety: Full Pydantic model validation
  • Error handling: Detailed XplainableAPIError exceptions
  • IDE support: Complete autocompletion and type hints
1# Replace with your actual API key
2API_KEY = "" # Get from https://platform.xplainable.io/
3HOSTNAME = "https://platform.xplainable.io"
4
5try:
6 # Initialize the refactored client
7 client = XplainableClient(
8 api_key=API_KEY,
9 hostname=HOSTNAME
10 )
11
12 # Display connection info
13 info = client.connection_info
14 print(f"Connected successfully!")
15 print(f"User: {info['username']}")
16 print(f"Hostname: {info['hostname']}")
17 print(f"Xplainable Version: {info['xplainable_version']}")
18 print(f"Python Version: {info['python_version']}")
19
20 # Test service availability
21 services = ['models', 'deployments', 'preprocessing', 'collections',
22 'datasets', 'inference', 'gpt', 'autotrain', 'misc']
23
24 print(f"
25Available services:")
26 for service in services:
27 if hasattr(client, service):
28 print(f" ✓ {service}")
29 else:
30 print(f" ✗ {service}")
31
32except XplainableAPIError as e:
33 print(f"API Error: {e.message}")
34 if e.status_code == 401:
35 print("Please check your API key")
36 elif e.status_code == 403:
37 print("Check your permissions")
38except Exception as e:
39 print(f"Connection failed: {str(e)}")
40 print("Make sure to replace 'your-api-key-here' with your actual API key")

System Health Check

Using the Misc Service to verify system connectivity and performance.

1try:
2 # Test server connectivity
3 print("Testing server connectivity...")
4
5 # Ping gateway
6 gateway_ping = client.misc.ping_gateway()
7 print(f"Gateway ping: {'✓' if gateway_ping.success else '✗'} ({gateway_ping.response_time:.3f}s)")
8
9 # Try server ping (may not be available in all environments)
10 try:
11 server_ping = client.misc.ping_server()
12 print(f"Server ping: {'✓' if server_ping.success else '✗'} ({server_ping.response_time:.3f}s)")
13 except XplainableAPIError as e:
14 print(f"Server ping: Not available ({e.status_code})")
15
16 # Get version information
17 version_info = client.misc.get_version_info()
18 print(f"
19Version Information:")
20 print(f" • Xplainable: {version_info.xplainable_version}")
21 print(f" • Python: {version_info.python_version}")
22
23except XplainableAPIError as e:
24 print(f"Health check warning: {e.message}")
25except Exception as e:
26 print(f"Health check failed: {str(e)}")

Load Telco Churn Dataset

Using the Datasets Service to explore available datasets and load the Telco data.

1try:
2 # Try to list available public datasets
3 print("Checking available public datasets...")
4 datasets = client.datasets.list_datasets()
5 print(f"Found {len(datasets)} public datasets:")
6
7 # Show first few datasets
8 for i, dataset in enumerate(datasets[:5]):
9 print(f" {i+1}. {dataset}")
10
11 if len(datasets) > 5:
12 print(f" ... and {len(datasets) - 5} more")
13
14except XplainableAPIError as e:
15 print(f"Dataset service warning: {e.message}")
16except Exception as e:
17 print(f"Dataset service info: {str(e)}")
18
19# Load the Telco dataset directly (primary method)
20print("
21Loading IBM Telco Customer Churn dataset...")
22try:
23 df = pd.read_csv('https://xplainable-public-storage.syd1.digitaloceanspaces.com/example_data/telco_customer_churn.csv')
24 print(f"Successfully loaded dataset with shape: {df.shape}")
25 print(f"Columns: {list(df.columns[:5])}{'...' if len(df.columns) > 5 else ''}")
26
27 # Display sample
28 print("
29Sample data:")
30 display(df.head())
31
32except Exception as e:
33 print(f"Failed to load dataset: {str(e)}")
34 # Create sample data for demonstration
35 print("Creating sample data for demonstration...")
36 df = pd.DataFrame({
37 'CustomerID': [f'C{i:04d}' for i in range(100)],
38 'Gender': np.random.choice(['Male', 'Female'], 100),
39 'Tenure Months': np.random.randint(1, 72, 100),
40 'Monthly Charges': np.random.uniform(20, 120, 100),
41 'Churn Label': np.random.choice(['Yes', 'No'], 100)
42 })
43 print(f"Created sample dataset with shape: {df.shape}")

AI-Powered Dataset Analysis with Autotrain

Using the Autotrain Service to get AI-powered insights about our dataset.

1# Prepare data for autotrain analysis
2print("Starting AI-powered dataset analysis...")
3
4try:
5 # Save a sample of the dataset for analysis
6 sample_df = df.sample(min(1000, len(df))) # Use sample for faster processing
7 temp_file = "/tmp/telco_sample.csv"
8 sample_df.to_csv(temp_file, index=False)
9
10 # Configure AI text generation
11 textgen_config = TextGenConfig(
12 model="gpt-4o-mini",
13 temperature=0.7,
14 max_tokens=1000
15 )
16
17 print(f"Analyzing dataset sample ({len(sample_df)} rows)...")
18
19 # Get AI-powered dataset summary
20 try:
21 summary = client.autotrain.summarize_dataset(
22 file_path=temp_file,
23 textgen_config=textgen_config
24 )
25
26 print(f"Dataset Analysis Complete!")
27 print(f"Columns: {len(summary.columns)}")
28 print(f"Rows: {summary.rows:,}")
29 print(f"Data Types: {len(set(summary.dtypes.values()))} unique types")
30
31 # Show missing values
32 missing_data = {k: v for k, v in summary.missing_values.items() if v > 0}
33 if missing_data:
34 print(f"Missing Values: {missing_data}")
35 else:
36 print(f"No missing values detected")
37
38 except XplainableAPIError as e:
39 print(f"Autotrain analysis not available: {e.message}")
40 print(f"Status: {e.status_code} - This is expected if autotrain endpoints are not fully implemented")
41
42 # Create manual summary for continuation
43 summary = DatasetSummary(
44 columns=list(df.columns),
45 rows=len(df),
46 dtypes=df.dtypes.astype(str).to_dict(),
47 missing_values=df.isnull().sum().to_dict()
48 )
49 print(f"Manual summary created for continuation")
50
51except Exception as e:
52 print(f"Autotrain service info: {str(e)}")
53 # Continue with manual analysis
54 summary = DatasetSummary(
55 columns=list(df.columns),
56 rows=len(df),
57 dtypes=df.dtypes.astype(str).to_dict(),
58 missing_values=df.isnull().sum().to_dict()
59 )
60
61print(f"
62Proceeding with data preprocessing...")

Data Preprocessing Pipeline

Creating and managing preprocessing pipelines with the Preprocessing Service.

1# Prepare the data
2print("Setting up data preprocessing pipeline...")
3
4# Convert target to binary
5df["Churn Label"] = df["Churn Label"].map({"Yes": 1, "No": 0})
6print(f"Target variable converted to binary: {df['Churn Label'].value_counts().to_dict()}")
7
8# Create preprocessing pipeline spec
9preprocessing_spec = PipelineSpec(steps=[
10 # Standardize text cases
11 StepSpec(
12 type="TextCleanTransformer",
13 columns=['City', 'Gender', 'Senior Citizen', 'Partner', 'Dependents',
14 'Phone Service', 'Multiple Lines', 'Internet Service',
15 'Online Security', 'Online Backup', 'Device Protection', 'Tech Support',
16 'Streaming TV', 'Streaming Movies', 'Contract', 'Paperless Billing',
17 'Payment Method'],
18 params={"operations": ["lowercase"]}
19 ),
20
21 # Condense low-frequency categories
22 StepSpec(
23 type="CategoryCondenseTransformer",
24 columns=["City"],
25 params={"min_frequency": 0.25}
26 ),
27
28 # Ensure proper data types
29 StepSpec(
30 type="TypeCastTransformer",
31 params={"dtypes": {"Monthly Charges": "float"}}
32 ),
33
34 # Remove unnecessary columns
35 StepSpec(
36 type="DropColumnsTransformer",
37 params={"columns": [
38 'CustomerID', # High cardinality
39 "Total Charges", # Multicollinearity with Tenure
40 'Count', # Single value
41 "Country", # Single value
42 "State", # Single value
43 "Zip Code", # High cardinality
44 "Lat Long", # High cardinality
45 "Latitude", # High cardinality
46 "Longitude", # High cardinality
47 "Churn Value", # Data leakage
48 "Churn Score", # Data leakage
49 "CLTV", # Data leakage
50 "Churn Reason", # Data leakage
51 ]}
52 ),
53])
54
55print(f"Pipeline spec created with {len(preprocessing_spec.steps)} steps")
56
57# Compile and apply preprocessing
58print("Compiling and applying preprocessing pipeline...")
59pipeline = compile_spec(preprocessing_spec)
60df_transformed = pipeline.fit_transform(df)
61print(f"Preprocessing complete!")
62print(f"Original shape: {df.shape} → Processed shape: {df_transformed.shape}")
63
64# Display processed data sample
65print("
66Processed data sample:")
67display(df_transformed.head())

Save Preprocessing Pipeline to Cloud

Using the Preprocessing Service with proper error handling.

1try:
2 print("Saving preprocessing pipeline to Xplainable Cloud...")
3
4 # Create preprocessor with type-safe response using PipelineSpec
5 preprocessor_id, preprocessor_version_id = client.preprocessing.create_preprocessor(
6 name=f"Telco Churn Preprocessing - v{xp.__version__} - New Client",
7 description="Complete preprocessing pipeline for IBM Telco Churn Dataset with refactored client",
8 spec=preprocessing_spec.model_dump(),
9 sample_df=df,
10 )
11
12 print(f"Preprocessor saved successfully!")
13 print(f"Preprocessor ID: {preprocessor_id}")
14 print(f"Version ID: {preprocessor_version_id}")
15
16 # Test loading the preprocessor back
17 print("
18Testing preprocessor reload...")
19 try:
20 pp_cloud = client.preprocessing.load_pipeline(preprocessor_version_id)
21 print(f"Preprocessor reloaded successfully!")
22 print(f"Pipeline: {pp_cloud}")
23
24 except XplainableAPIError as e:
25 print(f"Preprocessor reload warning: {e.message} (Status: {e.status_code})")
26
27except XplainableAPIError as e:
28 print(f"Preprocessor save warning: {e.message}")
29 print(f"Status: {e.status_code} - Continuing with local pipeline")
30 preprocessor_id, preprocessor_version_id = "local-pipeline", "local-version"
31
32except Exception as e:
33 print(f"Preprocessing service info: {str(e)}")
34 preprocessor_id, preprocessor_version_id = "local-pipeline", "local-version"

Model Training and Optimization

Training an XClassifier with hyperparameter optimization.

1# Prepare training data
2print("Preparing training data...")
3
4X = df_transformed.drop(columns=['Churn Label'])
5y = df_transformed['Churn Label']
6
7# Train/test split
8X_train, X_test, y_train, y_test = train_test_split(
9 X, y, test_size=0.33, random_state=42, stratify=y
10)
11
12print(f"Data split complete:")
13print(f" Training: {X_train.shape[0]:,} samples")
14print(f" Testing: {X_test.shape[0]:,} samples")
15print(f" Features: {X_train.shape[1]}")
16print(f" Class balance: {dict(y_train.value_counts())}")
17
18# Hyperparameter optimization
19print("
20Starting hyperparameter optimization...")
21try:
22 opt = XParamOptimiser()
23 params = opt.optimise(X_train, y_train)
24 print(f"Optimization complete!")
25 print(f"Best parameters: {list(params.keys())}")
26
27except Exception as e:
28 print(f"Optimization failed, using defaults: {str(e)}")
29 params = {}
30
31# Train the model
32print("
33Training XClassifier...")
34model = XClassifier(**params)
35model.fit(X_train, y_train)
36
37print(f"Model training complete!")
38print(f"Model type: {type(model).__name__}")

Model Explainability

Generate model explanations and insights.

1# Generate model explanations
2print("Generating model explanations...")
3
4try:
5 # Generate explanation visualization
6 explanation = model.explain()
7 print(f"Model explanation generated successfully!")
8
9 # Display explanation (this will show the interactive chart)
10 display(explanation)
11
12 # Get feature importances for analysis
13 if hasattr(model, 'feature_importances'):
14 importances = model.feature_importances
15 print(f"
16Top 5 Most Important Features:")
17 for i, (feature, importance) in enumerate(sorted(importances.items(), key=lambda x: x[1], reverse=True)[:5]):
18 print(f" {i+1}. {feature}: {importance:.4f}")
19
20except Exception as e:
21 print(f"Explanation generation failed: {str(e)}")
22 print(f"Model still trained successfully and ready for deployment")

Save Model to Cloud

Using the Models Service with type-safe operations and error handling.

1try:
2 print("Saving model to Xplainable Cloud...")
3
4 # Create model with type-safe response
5 model_id, model_version_id = client.models.create_model(
6 model=model,
7 model_name=f"Telco Churn Classifier - v{xp.__version__}",
8 model_description="Advanced churn prediction model using XClassifier with the refactored client",
9 x=X_train,
10 y=y_train
11 )
12
13 print(f"Model saved successfully!")
14 print(f"Model ID: {model_id}")
15 print(f"Version ID: {model_version_id}")
16
17 # Test model information retrieval
18 try:
19 print("
20Retrieving model information...")
21 model_info = client.models.get_model(model_id)
22 print(f"Model info retrieved:")
23 print(f" Name: {model_info.model_name}")
24 print(f" Description: {model_info.model_description}")
25
26 except XplainableAPIError as e:
27 print(f"Model info retrieval warning: {e.message} (Status: {e.status_code})")
28
29except XplainableAPIError as e:
30 print(f"Model save warning: {e.message}")
31 print(f"Status: {e.status_code} - Continuing with local model")
32 model_id, model_version_id = "local-model", "local-version"
33
34except Exception as e:
35 print(f"Models service info: {str(e)}")
36 model_id, model_version_id = "local-model", "local-version"

Model Deployment

Using the Deployments Service with comprehensive error handling.

1try:
2 print("Deploying model...")
3
4 # Deploy the model with type-safe response
5 deployment_response: CreateDeploymentResponse = client.deployments.deploy(model_version_id)
6 deployment_id = deployment_response.deployment_id
7
8 print(f"Model deployed successfully!")
9 print(f"Deployment ID: {deployment_id}")
10
11 # Generate deployment key
12 try:
13 print("
14Generating deployment key...")
15 deploy_key = client.deployments.generate_deploy_key(
16 deployment_id=deployment_id,
17 description="Telco Churn Prediction API - Refactored Client Demo",
18 days_until_expiry=30
19 )
20
21 print(f"Deployment key generated!")
22 print(f"Key: {str(deploy_key)[:16]}...[truncated]")
23 print(f"Expires in: 30 days")
24
25 except XplainableAPIError as e:
26 print(f"Deploy key generation warning: {e.message} (Status: {e.status_code})")
27 deploy_key = None
28
29 # List deployments
30 try:
31 print("
32Listing team deployments...")
33 deployments = client.deployments.list_deployments()
34 print(f"Found {len(deployments)} deployment(s):")
35
36 for i, dep in enumerate(deployments[:3]): # Show first 3
37 print(f" {i+1}. {dep.deployment_id} (Active: {dep.active})")
38
39 except XplainableAPIError as e:
40 print(f"Deployment listing warning: {e.message} (Status: {e.status_code})")
41
42except XplainableAPIError as e:
43 print(f"Deployment warning: {e.message}")
44 print(f"Status: {e.status_code}")
45
46 if e.status_code == 403:
47 print(f"This might be due to deployment quota limits")
48 elif e.status_code == 404:
49 print(f"Model version might not exist on the server")
50
51 deployment_id = None
52 deploy_key = None
53except Exception as e:
54 print(f"Deployment service info: {str(e)}")
55 deployment_id = None
56 deploy_key = None

Model Inference and Predictions

Using the Inference Service for predictions and explanations.

1try:
2 print("Testing model inference...")
3
4 # Prepare test data
5 test_sample = X_test.sample(3) # Get 3 random samples
6 print(f"Testing with {len(test_sample)} samples")
7
8 # Method 1: Local predictions (always available)
9 print("
10Local Inference:")
11 local_predictions = model.predict(test_sample)
12 local_probabilities = model.predict_proba(test_sample)
13
14 print(f"Local predictions: {local_predictions.tolist()}")
15 print(f"Churn probabilities: {[f'{p:.3f}' for p in local_probabilities[:, 1]]}")
16
17 # Method 2: File-based API inference (using the refactored client)
18 if model_id and model_version_id:
19 try:
20 print("
21File-based API Inference:")
22
23 # Save test sample to CSV file for API prediction
24 temp_file = "/tmp/test_sample.csv"
25 test_sample.to_csv(temp_file, index=False)
26
27 # Make predictions via API using the predict method
28 api_predictions = client.inference.predict(
29 filename=temp_file,
30 model_id=model_id,
31 version_id=model_version_id,
32 threshold=0.5,
33 delimiter=","
34 )
35
36 print(f"API predictions successful!")
37 print(f"API response type: {type(api_predictions)}")
38
39 # Clean up temp file
40 import os
41 try:
42 os.remove(temp_file)
43 except:
44 pass
45
46 except Exception as e:
47 print(f"API inference warning: {str(e)}")
48
49 else:
50 print("
51API inference skipped (no model ID available)")
52
53 # Display prediction results
54 print("
55Prediction Summary:")
56 for i, (idx, row) in enumerate(test_sample.iterrows()):
57 local_pred = local_predictions[i]
58 local_prob = local_probabilities[i, 1]
59
60 print(f" Sample {i+1}:")
61 print(f" Prediction: {'Churn' if local_pred == 1 else 'No Churn'}")
62 print(f" Probability: {local_prob:.3f}")
63 print(f" Monthly Charges: ${row['Monthly Charges']:.2f}")
64 print(f" Tenure: {row['Tenure Months']} months")
65
66except Exception as e:
67 print(f"Inference service info: {str(e)}")

AI-Powered Insights with GPT Service

Using the GPT Service to generate intelligent reports and insights.

1try:
2 print("Generating AI-powered insights...")
3
4 # Generate model report
5 try:
6 print("Creating model report...")
7 report = client.gpt.generate_report(
8 model_id=model_id,
9 version_id=model_version_id,
10 target_description="Customer churn likelihood (1 = will churn, 0 = will stay)",
11 project_objective="Identify customers at risk of leaving to improve retention strategies",
12 max_features=10,
13 temperature=0.7
14 )
15
16 print(f"AI report generated!")
17 print(f"Report length: {len(report.report):,} characters")
18
19 if report.key_insights:
20 print(f"Key insights: {len(report.key_insights)}")
21
22 # Display report (truncated)
23 print(f"
24Report Preview:")
25 print(f"{report.report[:500]}...")
26
27 except XplainableAPIError as e:
28 print(f"GPT report warning: {e.message} (Status: {e.status_code})")
29
30 # Generate model explanation
31 try:
32 print("
33Creating natural language explanation...")
34 explanation = client.gpt.explain_model(
35 model_id=model_id,
36 version_id=model_version_id,
37 language="en",
38 detail_level="medium"
39 )
40
41 print(f"AI explanation generated!")
42 print(f"
43Model Explanation:")
44 print(f"{explanation.explanation[:400]}...")
45
46 except XplainableAPIError as e:
47 print(f"GPT explanation warning: {e.message} (Status: {e.status_code})")
48
49 # Manual insights (always available)
50 print(f"
51Manual Model Analysis:")
52 print(f" Training Data: {len(X_train):,} samples")
53 print(f" Features Used: {X_train.shape[1]}")
54 print(f" Class Distribution: {dict(y_train.value_counts())}")
55
56 if hasattr(model, 'feature_importances'):
57 top_feature = max(model.feature_importances.items(), key=lambda x: x[1])
58 print(f" Most Important Feature: {top_feature[0]} ({top_feature[1]:.3f})")
59
60except Exception as e:
61 print(f"GPT service info: {str(e)}")
62 print(f"Manual analysis available above")

Collections and Organization

Using the Collections Service to organize models.

1try:
2 print("Creating model collection...")
3
4 # Create a collection for churn models
5 try:
6 collection_response = client.collections.create_collection(
7 model_id=model_id,
8 name="Churn Prediction Models",
9 description="Collection of customer churn prediction models for retention strategies"
10 )
11
12 collection_id = collection_response.collection_id
13 print(f"Collection created!")
14 print(f"Collection ID: {collection_id}")
15
16 # Create scenarios using sample data
17 try:
18 print("
19Creating prediction scenarios...")
20
21 # First, get the model partitions to get a valid partition_id
22 try:
23 partitions = client.models.list_model_version_partitions(model_version_id)
24 if partitions and len(partitions.get('partitions', [])) > 0:
25 partition_id = partitions['partitions'][0]['partition_id']
26 print(f" Using partition ID: {partition_id}")
27 else:
28 print(" No partitions found, skipping scenario creation")
29 raise Exception("No valid partition found")
30 except Exception as e:
31 print(f" Could not get partitions: {str(e)}")
32 raise
33
34 # Take 5 random samples from test data for scenarios
35 sample_scenarios = X_test.sample(5)
36
37 # Create scenario data with predictions (one by one to match API structure)
38 created_scenarios = []
39 for idx, (_, row) in enumerate(sample_scenarios.iterrows()):
40 try:
41 # Get prediction for this sample - convert to DataFrame for consistency
42 sample_df = row.to_frame().T # Convert Series to single-row DataFrame
43 sample_prediction = model.predict(sample_df)
44 sample_probability = model.predict_proba(sample_df)
45
46 # Handle both scalar and array predictions
47 if hasattr(sample_prediction, '__len__') and len(sample_prediction) > 0:
48 pred_value = float(sample_prediction[0])
49 else:
50 pred_value = float(sample_prediction)
51
52 # Handle probability array
53 if hasattr(sample_probability, '__len__') and len(sample_probability) > 0:
54 if hasattr(sample_probability[0], '__len__') and len(sample_probability[0]) > 1:
55 prob_value = float(sample_probability[0][1]) # Churn probability
56 else:
57 prob_value = float(sample_probability[0])
58 else:
59 prob_value = float(sample_probability)
60
61 # Determine risk level
62 risk_level = "High" if prob_value > 0.7 else "Medium" if prob_value > 0.3 else "Low"
63
64 # Create individual scenario matching API structure
65 scenario_data = {
66 "version_id": model_version_id,
67 "partition_id": partition_id, # Use the actual partition ID
68 "scenario": row.to_dict(), # The actual feature data
69 "score": pred_value,
70 "proba": prob_value,
71 "multiplier": 1.0, # Default multiplier value
72 "support": 0, # Default support value
73 "notes": f"Customer Scenario {idx + 1}: {row['Contract']} contract, ${row['Monthly Charges']:.2f}/month, Risk: {risk_level}"
74 }
75
76 except Exception as pred_error:
77 print(f" Prediction error for scenario {idx + 1}: {str(pred_error)}")
78 # Create a basic scenario without predictions
79 scenario_data = {
80 "version_id": model_version_id,
81 "partition_id": partition_id, # Use the actual partition ID
82 "scenario": row.to_dict(),
83 "score": 0.0,
84 "proba": 0.5, # Default neutral probability
85 "multiplier": 1.0, # Default multiplier value
86 "support": 0, # Default support value
87 "notes": f"Customer Scenario {idx + 1}: {row['Contract']} contract, ${row['Monthly Charges']:.2f}/month (prediction failed)"
88 }
89
90 # Create single scenario (since API expects individual scenarios)
91 try:
92 created_scenario = client.collections.create_scenarios(
93 collection_id=collection_id,
94 scenarios=[scenario_data] # Single scenario in list
95 )
96 created_scenarios.extend(created_scenario)
97 print(f" Created scenario {idx + 1}: Risk Level {risk_level}")
98 except Exception as e:
99 print(f" Failed to create scenario {idx + 1}: {str(e)}")
100 continue
101
102 print(f"Created {len(created_scenarios)} scenarios total!")
103
104 except XplainableAPIError as e:
105 print(f"Scenario creation warning: {e.message} (Status: {e.status_code})")
106
107 # List team collections
108 try:
109 print(f"
110Listing team collections...")
111 collections = client.collections.get_team_collections()
112 print(f"Found {len(collections)} team collection(s)")
113
114 for collection in collections[-3:]: # Show last 3
115 print(f" {collection.get('name', 'Unnamed')} (ID: {collection.get('id', 'unknown')})")
116
117 except XplainableAPIError as e:
118 print(f"Collection listing warning: {e.message} (Status: {e.status_code})")
119
120 # Get collection scenarios
121 try:
122 print(f"
123Retrieving collection scenarios...")
124 scenarios = client.collections.get_collection_scenarios(collection_id)
125 print(f"Found {len(scenarios)} scenario(s) in collection")
126
127 except XplainableAPIError as e:
128 print(f"Scenario retrieval warning: {e.message} (Status: {e.status_code})")
129
130 except XplainableAPIError as e:
131 print(f"Collection creation warning: {e.message} (Status: {e.status_code})")
132 collection_id = None
133
134except Exception as e:
135 print(f"Collections service info: {str(e)}")
136 collection_id = None